package com.liusy.code.popup.actions;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;

import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.jface.action.IAction;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.dialogs.ProgressMonitorDialog;
import org.eclipse.jface.operation.IRunnableWithProgress;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.IObjectActionDelegate;
import org.eclipse.ui.IWorkbenchPart;

import com.liusy.code.PluginBean;
import com.liusy.code.ProjectBean;
import com.liusy.code.Tools;

public class BuildEnvironmentAction implements IObjectActionDelegate
{
	private Shell shell;
	private ProjectBean projectBean;

	public BuildEnvironmentAction()
	{
		super();
	}

	@Override
	public void setActivePart(IAction action, IWorkbenchPart targetPart)
	{
		shell = targetPart.getSite().getShell();
	}

	@Override
	public void run(IAction action)
	{
		boolean flag = MessageDialog.openQuestion(shell, "slave4j", "是否搭建开发环境？");
		if (flag)
		{
			//环境搭建
			ProgressMonitorDialog progressDialog = new ProgressMonitorDialog(shell);

			IRunnableWithProgress runnable = new IRunnableWithProgress()
			{
				public void run(IProgressMonitor monitor) throws InvocationTargetException, InterruptedException
				{
					monitor.beginTask("搭建开发环境,请稍等......", 2);

					try
					{
						//第一步：向WebRoot中导入所需的文件
						monitor.worked(1);
						monitor.subTask("向" + projectBean.getWebRootName() + "中导入所需的文件");
						Tools.copyFileToProject(PluginBean.getWebRoot(), projectBean.getWebRoot());
						//第二步：向classpath中导入所需的文件
						monitor.worked(1);
						monitor.subTask("向src中导入所需的文件");
						Tools.copyFileToProject(PluginBean.getSrc(), projectBean.getSrc());
					} catch (IOException e)
					{
						e.printStackTrace();
					}

					monitor.done();
				}
			};

			try
			{
				progressDialog.run(true, false, runnable);
			} catch (InvocationTargetException e)
			{
				e.printStackTrace();
			} catch (InterruptedException e)
			{
				e.printStackTrace();
			}

			/**
			 * 刷新工程
			 */
			projectBean.refresh();
		}
	}

	@Override
	public void selectionChanged(IAction action, ISelection selection)
	{
		projectBean = new ProjectBean(selection);
	}

}
